package com.ala4.oxcafe.boot.interceptor;

import com.ala4.oxcafe.common.utils.text.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 打印除了body的其他参数
 *
 * @author PING
 * @version 1.0
 * @date 2024/12/6 12:44
 */
@Slf4j
public class WebLoggerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws IOException {
        // 查询参数
        String queryString = request.getQueryString();
        //获取全部的请求参数-除了body的参数
        Enumeration<String> em = request.getParameterNames();
        Map<String, String> params = new HashMap<>();
        while (em.hasMoreElements()) {
            String name = em.nextElement();
            // 查询字符串里面没有包含这个名称的才打印
            if (!Objects.isNull(queryString) && !queryString.contains(name)) {
                String value = request.getParameter(name);
                params.put(name, value);
            }
        }

        String requestURI = request.getMethod() + ":" + request.getRequestURI();
        if (StrUtil.isNotEmpty(queryString)) {
            requestURI = requestURI + "?" + request.getQueryString();
        }
        log.info("开始请求接口[{}]", requestURI);

        if (handler instanceof HandlerMethod h) {
            log.info("Controller: {}.{}", h.getBean().getClass().getName(), h.getMethod().getName());
        }

        if (StrUtil.isNotEmpty(queryString)) {
            log.info("Query     : {}", queryString);
        }
        if (!params.isEmpty()) {
            log.info("Params    : {}", params);
        }

        request.setAttribute("_startTime", System.currentTimeMillis());
        request.setAttribute("_requestURI", requestURI);

        return true;
    }

    @Override
    public void postHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler,
                           @NonNull @Nullable ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, @NonNull Exception ex) throws Exception {
        Long startTime = (Long) request.getAttribute("_startTime");
        String requestURI = (String) request.getAttribute("_requestURI");
        log.info("结束请求接口[{}],耗时[{}ms]", requestURI, System.currentTimeMillis() - startTime);
    }
}
